<template>
  <div class="service-page">
    <el-dialog class="save-img-dialog" :title="$t('保存图片')" :visible.sync="centerDialogVisible" width="90%" center>
      <el-image :src="src" fit="fill"></el-image>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">{{
          $t("取消")
          }}</el-button>
        <el-button type="primary" @click="saveImage">{{
          $t("保存图片")
          }}</el-button>
      </span>
    </el-dialog>
    <div class="container-m">
      <div class="search">
        <el-input :placeholder="$t('搜索订单')" prefix-icon="el-icon-search" v-model="searchText" @input="handleSearch">
        </el-input>
      </div>
      <div class="list">
        <div v-for="(item, index) in orderList" :key="index" ref="imgBox" class="item">
          <el-card class="box-card" shadow="never">
            <div class="p">{{ $t("服务名称") }}: #{{ item.service_id }} {{ item.service_theme }} </div>
            <div class="p">{{ $t("订单编号") }}: {{ item.id }} </div>
            <!-- <div class="p">{{ $t("订单输入") }}: {{ item.imei }} </div> -->
            <div class="p">
              状态:
              <el-tag size="small" effect="dark" :type="stateType[item.ap_result]">{{ stateMapping(item.ap_result)
                }}</el-tag>
              <el-tag size="small" effect="dark" type="warning" style="margin-left: 10px"
                @click="copyToClipboard(index)">复制结果</el-tag>
              <el-tag size="small" effect="dark" type="danger" style="margin-left: 10px"
                @click="cutImage(index)">生成图片</el-tag>
            </div>
            <div class="p" ref="copy" v-html="item.result"></div>
            <div class="p">提交时间: {{ item.create_time }}</div>
            <div class="p">更新时间: {{ item.update_time }}5</div>
            <div class="p">消耗积分: {{ item.price }}</div>
            <div class="p2" @click="orderFeedBack(item)">对订单有疑问</div>
          </el-card>
        </div>

        <div v-if="!(orderList && orderList.length)" style="text-align: center;color: #999;padding: 20px;">暂无数据</div>
      </div>
    </div>
  </div>
</template>

<script>
import apiService from "@/api/apiService";
import { stateColor, stateMapping, changeToBlob } from "@/utils";
import html2canvas from "html2canvas";

export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "OrderInfo",
  data() {
    return {
      stateType: {
        0: "",
        1: "info",
        2: "success",
        3: "warning",
        4: "danger",
      },
      searchText: "",
      cutIgnore: "cut-ignore",
      showNecessaryElement: false,
      centerDialogVisible: false,
      orderId: "",
      orderResult: "",
      orderList: [],
      src: "",
    };
  },
  mounted() {
    this.getList()
    // 有可能是批ID(6位)， 也有可能是订单ID
    this.orderId = this.$route.query.goParam;
    if (this.orderId !== undefined && this.orderId !== "") {
      apiService.get("/order-info?id=" + this.orderId).then((res) => {
        if (res.code === 0) {
          this.orderList = res.data ?? [];
          // this.processResult(res.data.ap_result, res.data.result)
        }
      });
    }
  },
  methods: {
    handleSearch() {
      this.getList()
    },
    getList() {
      this.orderId = this.searchText;
      if (this.orderId !== undefined && this.orderId !== "") {
        apiService.get("/order-info?id=" + this.orderId).then((res) => {
          if (res.code === 0) {
            this.orderList = res.data;
            // this.processResult(res.data.ap_result, res.data.result)
          }
        });
      }
    },
    orderFeedBack(row) {
      apiService
        .get("/order-feedback?id=" + row.id)
        .then((res) => {
          if (res.code === 0) {
            row.manualOrderType = 1;
            this.$message.success(res.data);
          }
        })
    },
    hasFeedBack(manualOrderType) {
      return manualOrderType === 1;
    },
    saveImage() {
      const link = document.createElement("a"); // 创建一个超链接对象实例
      link.download = "order" + this.orderId + ".png"; // 设置要下载的图片的名称
      link.href = this.href; // 将图片的URL设置到超链接的href中
      link.click(); // 触发超链接的点击事件
      this.centerDialogVisible = false;
    },
    cutImage(index) {
      const imgBox = this.$refs.imgBox[index];
      this.showNecessaryElement = true;
      const logoUrl = require("@/assets/images/cut_03.png");
      const img = new Image();
      img.setAttribute("style", "width: 100%;");
      img.src = logoUrl;
      let textWidth = imgBox.clientWidth;
      let textHeight = imgBox.clientHeight;
      let imgWidth = 0;
      let imgHeight = 0;
      img.onload = () => {
        imgWidth = imgBox.clientWidth;
        imgHeight = (imgWidth * img.height) / img.width;
        html2canvas(imgBox, {
          ignoreElements: function (element) {
            return element.classList.contains("cut-ignore");
          },
          height: imgHeight,
          width: imgWidth,
          scale: 2, // 使用设备像素比或者自定义的比例，如2表示将画布放大2倍
        })
          .then((canvas) => {
            const canvas1 = document.createElement("canvas");
            canvas1.width = imgWidth;
            canvas1.height = imgHeight;
            const ctx1 = canvas1.getContext("2d");
            ctx1.drawImage(img, 0, 0, imgWidth, imgHeight);
            ctx1.drawImage(canvas, 40, 80, textWidth - 80, textHeight + 160);
            let dataURL = canvas1.toDataURL("image/png");
            var blob = this.changeToBlob(dataURL); //获取blob对象
            var url = URL.createObjectURL(blob);
            this.href = canvas1.toDataURL();
            this.src = url;
            this.centerDialogVisible = true;
          })
          .finally(() => {
            this.showNecessaryElement = false;
          });
      };
    },
    //Base64 to Blob
    changeToBlob,
    stateColor,
    stateMapping,
    processResult(ap_result, result) {
      if (result) {
        this.orderResult = result.replace(/\\/g, "");
        return;
      }
      this.orderResult = "暂无结果";
    },
    copyToClipboard(index) {
      // const text = this.$refs.copy[index].textContent;
      let text = this.$refs.copy[index].innerHTML;
      text = text.replace(/<br>/g, '\n');
      text = this.removeHTMLTags(text)
      const input = document.createElement('textarea');
      input.value = text; // 设置要复制的文本
      document.body.appendChild(input);
      input.select(); // 选中文本
      document.execCommand('copy'); // 执行复制操作
      document.body.removeChild(input); // 移除临时的输入框
      this.$message.success('内容已复制到剪贴板');
    },
    removeHTMLTags(str) {
      return str.replace(/<[^>]*>/g, '');
    }
  },
};
</script>

<style lang="scss" scoped>
.service-page {
  min-height: 100vh;
  background-color: #f4f4f4;
  padding-top: 0.1rem;
}

.list {
  // box-shadow: 0 2px 10px rgba(0, 0, 0, .1);
  // background-color: #fff;
  // margin-top: .1rem;
  // border-radius: 8px;
  // padding: .1rem;

  .item {
    padding: 10px 0;

    .p {
      font-size: 0.14rem;
      color: #333;
      line-height: 1.8;
    }

    .p2 {
      height: 0.3rem;
      background-color: #e6e6e8;
      border-radius: 6px;
      margin-top: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #666;
      font-size: 0.14rem;
    }
  }
}

.logo-c {
  display: flex;
  text-align: center;
  width: fit-content;
}

.logo-n {
  line-height: 80px;
  height: 80px;
}

.margin-top-result .el-descriptions-item__label:not(.is-bordered-label) {
  margin-right: unset;
}
</style>
